// Package crons
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package crons

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/os/gtime"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/client"
	"hotgo/utility/tradeDate"
	"io"
	"net/http"
	url2 "net/url"
	"time"
)

func init() {
	cron.Register(LHB)
}

// LHB 测试任务（无参数）
var LHB = &cLHB{name: "lhb"}
var stockLhbGgtjSina = "http://127.0.0.1:8000/api/public/stock_lhb_detail_em"

// symbol=603928&date=20240510&flag=买入
var stockLhbGgtjSinaDetail = "http://127.0.0.1:8000/api/public/stock_lhb_stock_detail_em"

/*
*
"序号": 89,

	"代码": "900915",
	"名称": "中路B股",
	"上榜日": "2024-05-10T00:00:00.000Z",
	"解读": "普通席位卖出，成功率32.89%",
	"收盘价": 0.507,
	"涨跌幅": -7.4818,
	"龙虎榜净买额": -158672.37,
	"龙虎榜买入额": 133162.5,
	"龙虎榜卖出额": 291834.87,
	"龙虎榜成交额": 424997.37,
	"市场总成交额": 678850.0,
	"净买额占总成交比": -23.3737011122,
	"成交额占总成交比": 62.6054901672,
	"换手率": 1.5972,
	"流通市值": 4891911635.8,
	"上榜原因": "有价格涨跌幅限制的日收盘价格跌幅偏离值达到7%的前五只证券",
	"上榜后1日": null,
	"上榜后2日": null,
	"上榜后5日": null,
	"上榜后10日": null
*/
type stockLhbGgtjSinaResp struct {
	Code          string  `json:"代码"      `
	Name          string  `json:"名称"      `
	SumBuy        float64 `json:"龙虎榜买入额"    `
	SumSell       float64 `json:"龙虎榜卖出额"   `
	NetAmount     float64 `json:"龙虎榜净买额" `
	BuyLhb        float64 `json:"龙虎榜成交额"    `
	BuyMarket     float64 `json:"市场总成交额" `
	Date          string  `json:"上榜日"      `
	Desc          string  `json:"解读"      `
	Reason        string  `json:"上榜原因"    `
	Closed        float64 `json:"收盘价"   `
	ChangePercent float64 `json:"涨跌幅"   `
	SellSeat      *gjson.Json
	BuySeat       *gjson.Json
}

type stockLhbDetail struct {
	Name         string  `json:"name"`
	SumBuy       float64 `json:"sum_buy"`
	SumBuyRatio  float64 `json:"sum_buy_ratio"`
	SumSell      float64 `json:"sum_sell"`
	SumSellRatio float64 `json:"sum_sell_ratio"`
	NetAmount    int     `json:"net-amount"`
	Flag         string  `json:"flag"`
}

type stockLhbDetailResp struct {
	Name         string  `json:"交易营业部名称"`
	SumBuy       float64 `json:"买入金额"`
	SumBuyRatio  float64 `json:"买入金额-占总成交比例"`
	SumSell      float64 `json:"卖出金额"`
	SumSellRatio float64 `json:"卖出金额-占总成交比例"`
	NetAmount    int     `json:"净额"`
	Flag         string  `json:"类型"`
}
type cLHB struct {
	name string
}

func (c *cLHB) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cLHB) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	date := tradeDate.GetLatestDay()
	parse, _ := time.Parse(time.DateOnly, date)
	formatDate := gtime.New(parse).Format("Ymd")
	httpClient := client.GetClient()
	response, err := httpClient.Get(ctx, fmt.Sprintf("%s?start_date=%s&end_date=%s", stockLhbGgtjSina, formatDate, formatDate))
	//response, err := http.Get(fmt.Sprintf("%s?start_date=20240510&end_date=20240510", stockLhbGgtjSina))
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute http.Get err:%+v", err)
		return
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute io.ReadAll err:%+v", err)
		return err
	}
	var resp []stockLhbGgtjSinaResp
	err = json.Unmarshal(body, &resp)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
		return err
	}
	for _, emResp := range resp {
		// 龙虎榜上榜日期 2024-05-10T00:00:00.000Z
		//sellSeatDetail, _ := HttpGetLhbDetail(ctx, parser, emResp.Code, sbrq, "卖出")
		//buySeatDetail, _ := HttpGetLhbDetail(ctx, parser, emResp.Code, sbrq, "买入")
		err = service.SysStockLhbGgtjSina().Edit(ctx, &sysin.StockLhbGgtjSinaEditInp{
			StockLhbGgtjSina: entity.StockLhbGgtjSina{
				Code:          emResp.Code,
				Name:          emResp.Name,
				SumBuy:        emResp.SumBuy,
				SumSell:       emResp.SumSell,
				NetAmount:     emResp.NetAmount,
				BuyLhb:        emResp.BuyLhb,
				BuyMarket:     emResp.BuyMarket,
				Date:          parse.Format("2006-01-02"),
				Desc:          emResp.Desc,
				Reason:        emResp.Reason,
				Closed:        emResp.Closed,
				ChangePercent: emResp.ChangePercent,
			},
		})
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysStockZhASpotEm().Edit err:%+v", err)
			continue
		}
	}
	return
}

func HttpGetLhbDetail(ctx context.Context, parser *cron.Parser, code, sbrq, flag string) ([]stockLhbDetail, error) {
	url := fmt.Sprintf("%s?symbol=%s&date=%s&flag=%s", stockLhbGgtjSinaDetail, code, sbrq, url2.QueryEscape(flag))
	response, err := http.Get(url)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute http.Get err:%+v", err)
		return nil, err
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute io.ReadAll err:%+v", err)
		return nil, err
	}
	var resp []stockLhbDetailResp
	err = json.Unmarshal(body, &resp)
	if err != nil {
		parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
		return nil, err
	}
	var sellSeatDetail []stockLhbDetail
	for _, res := range resp {
		sellSeatDetail = append(sellSeatDetail, stockLhbDetail{
			Name:         res.Name,
			SumBuy:       res.SumBuy,
			SumBuyRatio:  res.SumBuyRatio,
			SumSell:      res.SumSell,
			SumSellRatio: res.SumSellRatio,
			NetAmount:    res.NetAmount,
			Flag:         res.Flag,
		})
	}
	return sellSeatDetail, nil
}
